package com.cloud.user.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import com.cloud.service.response.ResultResponse;
import com.cloud.service.util.BeanAndMapTransform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.cloud.service.dto.OrderDTO;
import com.cloud.user.dao.CustomerRepository;
import com.cloud.user.domain.Customer;
import com.cloud.user.feign.order.OrderClient;

/**
 * Customer Controller
 *
 * @author qinxh
 * @date 2019/07/26
 */
@RestController
@RequestMapping("/api/user")
public class CustomerResourceController {

    private final static String CODE = "000000";

	@PostConstruct
    public void init() {

        Customer customer = new Customer();
        customer.setUsername("steven");
        customer.setPassword("111111");
        customer.setRole("User");
        customerRepository.save(customer);
    }
	
	@Autowired
	private CustomerRepository customerRepository;
	
	@Autowired
	private OrderClient orderClient;
	
	@PostMapping("")
    public Customer create(@RequestBody Customer customer) {

	    return customerRepository.save(customer);
    }

    @GetMapping("")
    public List<Customer> getAll() {

        return customerRepository.findAll();
    }
    
    @GetMapping("/my")
    public Map<String, Object> getMyInfo() {

        Customer customer = customerRepository.findOneByUsername("steven");

        /** TIPS：feign不支持GET方法传递POJO，会报请求方式错误。为了遵循restful规范，可以使用Map来实现
         * 推荐使用SpringQueryMap注解解决feign的get传参方式
         */
        OrderDTO order= new OrderDTO();
        order.setId(1L);
        order.setTitle("this title");
        ResultResponse<List<OrderDTO>> listResultResponse = orderClient.get0(order);

        ResultResponse<OrderDTO> details = orderClient.details(1L);
        if(details == null || !CODE.equals(details.getCode() ) ){
            return null;
        }

        Map<String, Object> result = new HashMap<>(2);
        result.put("customer", customer);
        result.put("order", details.getData());

        return result;
    }
}
